package com.hqj.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.hqj.config.JwtUtils;
import com.hqj.entity.User;
import com.hqj.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 黄啟军
 * @version 1.0
 * @date 2020/8/2 0002
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        // 判断是否是JWT Token
        return token instanceof JwtToken;
    }

    /**
     * 授权认证查询权限并赋值返回
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 身份验证，验证token
     * 验证用户是否存在，如果存在则把用户信息返回给shiro
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        //获取用户ID
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        User user = userService.findById(Long.valueOf(userId));
        if (user==null){
            throw new UnknownAccountException("账户不存在");
        }else if (user.getStatus()==-1){
            throw new LockedAccountException("账户已被锁定");

        }
        //返回的用户信息
        AccountProfile accountProfile = new AccountProfile();
        //对象属性拷贝
        BeanUtil.copyProperties(user,accountProfile);
        //accountProfile--用户的基本信息，非私密的信息jwtToken--秘钥信息getName--获得主体和证书的领域
        return new  SimpleAuthenticationInfo(accountProfile,jwtToken.getCredentials(),getName());
    }
}
